/*
    Copyright (C) 2013 maik.jablonski@jease.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jfix.zk;

import jfix.util.I18N;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;

public abstract class Login extends Grid {

	Textfield loginField = new Textfield();
	Passwordfield passwordField = new Passwordfield();

	public abstract boolean loginPerformed(String login, String password);

	public Login() {
		this(I18N.get("Username"), I18N.get("Password"));
	}

	public Login(String loginLabel, String passwordLabel) {
		passwordField.setType("password");

		EventListener submitListener = new EventListener() {
			public void onEvent(Event e) {
				loginHandler();
			}
		};

		Button submitButton = new Button(I18N.get("Login"), Images.SystemUsers);
		submitButton.addEventListener(Events.ON_CLICK, submitListener);
		addEventListener(Events.ON_OK, submitListener);

		Button resetButton = new Button(I18N.get("Reset"), Images.ViewRefresh);
		resetButton.addEventListener(Events.ON_CLICK, new EventListener() {
			public void onEvent(Event e) {
				resetHandler();
			}
		});

		append(loginLabel, loginField);
		append(passwordLabel, passwordField);
		append("", submitButton, new Separator(Separator.VERTICAL), resetButton);
	}

	private void append(String label, Component... comp) {
		Cell labelCell = new Cell(new Label(label));
		labelCell.setHflex("2");
		Cell compCell = new Cell(comp);
		compCell.setHflex("4");
		add(labelCell, compCell);
	}

	private void loginHandler() {
		String loginText = loginField.getText().trim();
		String passwordText = passwordField.getText().trim();
		if (!"".equals(loginText) && !"".equals(passwordText)) {
			if (!loginPerformed(loginText, passwordText)) {
				passwordField.setValue(null);
				passwordField.focus();
			}
		}
	}

	private void resetHandler() {
		loginField.setValue(null);
		passwordField.setValue(null);
		loginField.focus();
	}
}
